package touro.mancala.master;

import java.net.Socket;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

import touro.mancala.slave.Board;

public class Request {

	private static final Logger logger = Logger.getLogger(Request.class.getName());
	
	private static final AtomicInteger NEXT_ID = new AtomicInteger(0);
	
	private final Board board;
	private final Socket toClient;
	private final int id;

	private Response bestAnswer=null;

	private int NumResponses;
	private int numChildren;

	
	public Request(Socket toClient, Board board) {
		super();
		this.toClient = toClient;
		this.board = board;
		this.id = NEXT_ID.incrementAndGet();

		NumResponses=0;
		LinkedList<Board> childrenBoards = board.getChildrenBoards();
		this.numChildren = childrenBoards.size();	

	}

	public Board getBoard() {
		return board;
	}

	public Socket getToClient() {
		return toClient;
	}

	public int getId() {
		return id;
	}
	

	public boolean processResponse(Response s){
		logger.log(Level.INFO,"Processing response");
		NumResponses++;
		if(bestAnswer==null){
			bestAnswer=s;
		}
		else{
			bestAnswer= s.getScore() >bestAnswer.getScore() ? s:bestAnswer;
		}
		return requestCompleted();
		
	}
	
	public boolean requestCompleted(){
		return NumResponses==getNumChildBoards();
	}
	

	public int getNumChildBoards(){
		return numChildren;
	}
	

	public Response getBestAnswer() {
		return bestAnswer;
	}
}
